<?php

class UserController extends UserBaseC {

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
                'minLength' => 4,
                'maxLength' => 4,
                'transparent' => true,
            ),
        );
    }

    //买家注册
    public function actionRegister() {
        //登录下不让注册
        if (Yii::app()->user->isLogged()) {
            $this->error('您已经登录，无法进行注册！');
        }
        $this->layout = 'theme.views.layouts.RegisterContent';
        $choise = isset($_GET['choise']) ? $_GET['choise'] : "";
        $model = new MembersModel('create');
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'reg-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
        // collect user input data
        if (isset($_POST['MembersModel'])) {
            $_POST['MembersModel']['kind'] = 1;
            $_POST['MembersModel']['username'] = $_POST['MembersModel']['email'];
            UserRegister::getInstance()->data($_POST['MembersModel']);
            $model->attributes = $_POST['MembersModel'];

            //邀请注册手机验证
            $invite = (int) Yii::app()->session['invite'];
            if (!empty($invite)) {
                $phone = $_POST['MembersModel']['phone'];
                $snscode = $_POST['snscode'];
                //手机号需要唯一
                if(MembersModel::getByPhone($phone)){
                    $this->error('该手机已经被注册！');
                }                 
                if (SnsVerification::getInstance()->verification($snscode, $phone, 'cellphone') !== true) {
                    $this->error('短信验证码错误！');
                }
            }
            if ($model->validate() && UserRegister::getInstance()->register()) {
                $email = urlencode($_POST['MembersModel']['email']);
                $this->redirect(array("/user/user/regemailsuccesed", 'mail' => $email));
            } else {
                $model->password = $_POST['MembersModel']['password'];
                $model->repassword = $_POST['MembersModel']['repassword'];
            }
        }
        //邀请注册
        $invite = (int) Yii::app()->request->getParam('invite');
        if (!empty($invite)) {
            $this->session('invite', $invite);
        }
        $this->render('register', array('model' => $model, 'choise' => $choise));
    }

    //商家注册
    public function actionRegMobile() {
        //登录下不让注册
        if (Yii::app()->user->isLogged()) {
            $this->error('您已经登录，无法进行注册！');
        }
        $this->layout = 'theme.views.layouts.RegisterContent';
        $choise = isset($_GET['choise']) ? $_GET['choise'] : "";
        $model = new MembersModel;
        $validators = array(
            array('wangwang', 'required', 'message' => '联系旺旺不能为空！'),
            array('username', 'required', 'message' => '手机号不能为空！'),
            array('username', 'unique', 'allowEmpty' => false, 'message' => '该手机已经被注册！'),
            array('email', 'required', 'message' => '邮箱不能为空！'),
            array('email', 'email', 'message' => '您输入的邮箱地址无效！'),
            array('email', 'unique', 'message' => '您输入的邮箱已被使用！'),
            array('password', 'length', 'tooShort' => '密码不能低于6位！', 'min' => 6),
            array('password', 'required', 'message' => '密码不能为空！'),
            array('group_id,type,status,regip,regdate,lastloginip,lastlogintime,kind', 'safe'),
            array('repassword', 'compare', 'compareAttribute' => 'password', 'message' => '两次输入密码不一致！'),
            array('agreement', 'in', 'range' => array(1), 'message' => '您必须同意《用户注册协议》！'),
            array('phone', 'safe'),
        );
        UserRegister::getInstance()->setValidators($validators);
        if (isset($_POST['MembersModel'])) {
            $moblie = $_POST['MembersModel']['username'];
            $snscode = $_POST['snscode'];
            $data = $_POST['MembersModel'];
            $data['repassword'] = $_POST['MembersModel']['repassword'];
            $data['phone'] = $moblie;
            $data['status'] = 1;
            $model->setValidators($validators);
            $model->attributes = $data;
            //手机号需要唯一
            if(MembersModel::getByPhone($moblie)){
                $this->error('该手机已经被注册！');
            }    

            if (!$model->validate()) {
                $this->error($model->getOneError() ? $model->getOneError() : '注册失败！');
            }
            UserRegister::getInstance()->data($data);
            if (SnsVerification::getInstance()->verification($snscode, $moblie, 'cellphone') !== true) {
                $this->error('短信验证码错误！注册商家不成功,可以先注册成为买家再升级为商家');
            }
            if ($uid = UserRegister::getInstance()->register()) {
                MembersTaobaoModel::model()->saveWangwang($uid, $_POST['MembersModel']['wangwang']);
                Yii::app()->user->login($data['username'], $data['repassword']);
                if (IS_AJAX) {
                    $this->success('注册成功！');
                } else {
                    $this->redirect(array("/user/info/index"));
                }
            } else {
                $this->error(UserRegister::getInstance()->getError());
            }
        }
        $this->render('regmobile', array('model' => $model, 'snscode' => $snscode, 'choise' => $choise));
    }

    protected function sentEmail($email) {
        $mail = Yii::createComponent('application.extensions.mailer.EMailer');
        $ConfigModel = new ConfigModel();
        $config = $ConfigModel->getConfig();
        $emailTitle = '亲爱的' . $config['sitename'] . '用户   ' . $email . "，请激活您的邮箱，完成注册";
        $code = substr(md5(uniqid(mt_rand(), true)), 0, 32);
        $url = $this->createUrl("/user/user/verify", array('confirmation_token' => $code));
        $emailBody = '
            <table width="720" border="0" cellspacing="0" cellpadding="0">
                      <tbody><tr>
                        <td height="40" style="line-height:24px">亲爱的<a href="mailto:' . $email . '" target="_blank">' . $email . '</a>：</td>
                      </tr>
                      <tr>
                        <td style="line-height:24px">感谢注册' . $config['sitename'] . '会员！<br>
                          请点击链接激活账号（链接48小时内有效）：<br>
                          <a href="' . Yii::app()->request->hostInfo . $url . '" target="_blank">' . Yii::app()->request->hostInfo . $url . '</a>
                          <br>
                          如果您的邮箱不支持链接点击，请将以上链接地址拷贝到您的浏览器地址栏中。<br>
                          如果您没有申请注册' . $config['sitename'] . '，请忽略此邮件
                        </td>
                      </tr>
                      <tr>
                        <td align="right" height="30">' . $config['sitename'] . '</td>
                      </tr>
                      <tr>
                        <td align="right"><span times="" t="5" style="border-bottom: 1px dashed rgb(204, 204, 204);">' . date('Y-m-d', time()) . '</span></td>
                      </tr>
                      <tr>
                        <td valign="middle" align="center" height="40" style="color:#999">（本邮件由系统自动发出，请勿回复。）</td>
                      </tr>
                    </tbody>
            </table>
            ';
        $MembersModel = new MembersModel();
        $member = $MembersModel->getMemberByEmail($email);
        if (!$member) {
            $_COOKIE['sent_email'] = '邮件尚未注册！';
            //Yii::app()->user->setFlash('sent_email', '邮件尚未注册！');
            return false;
        }
        $MembersActivationModel = new MembersActivationModel();
        if ($interval = $MembersActivationModel->JudgeSent($email)) {
            $interval = 120 - $interval;
            $_COOKIE['sent_email'] = "亲，您刚发送了一封邮件，请耐心等待！{$interval}秒后，还没收到请重发！";
            //Yii::app()->user->setFlash('sent_email', "亲，您刚发送了一封邮件，请耐心等待！{$interval}秒后，还没收到请重发！");
            return false;
        }
        if ($mail->sendEmail($email, $emailTitle, $emailBody)) {
            $endtime = $_SERVER['REQUEST_TIME'] + 48 * 3600;
            $MembersActivationModel->endtime = $endtime;
            $MembersActivationModel->status = 0;
            $MembersActivationModel->code = $code;
            $MembersActivationModel->email = $email;
            $MembersActivationModel->save();
            return true;
        }
        $_COOKIE['sent_email'] = "邮件发送失败！";
        //Yii::app()->user->setFlash('sent_email', '邮件发送失败！');
        return false;
    }

    public function actionRegEmailSuccesed() {
        $this->layout = 'theme.views.layouts.RegisterContent';
        $mail_host = false;
        $url = $this->createUrl("/user/user/regemailsuccesed/mail/{$_GET['mail']}");
        $email = urldecode($_GET['mail']);
        if ($this->sentEmail($email)) {
            $message = $email;
            $temp = explode('@', $email);
            $mail_host = $temp[1];
        } else {
            $message = $_COOKIE['sent_email'];
        }
        $this->render('regemailsuccesed', array('message' => $message, 'mail_host' => $mail_host, 'url' => $url));
    }

    public function actionVerify() {
        $MembersActivationModel = new MembersActivationModel();
        $code = $_GET['confirmation_token'];
        $message = $MembersActivationModel->JudgeVerify($code);
        if ($message['status'] == 0) {
            $email = urlencode($message['email']);
            $url = $this->createUrl("/user/user/regemailsuccesed", array('mail' => $email));
        } else if ($message['status'] == -1) {
            $url = $this->createUrl("/user/user/register");
        } else {
            $url = $this->createUrl("/user/login/login");
        }
        $this->render('verify', array('message' => $message, 'url' => $url));
    }

    public function actionFindPassword() {
        $model = new FindPasswordForm();
        if (isset($_POST['FindPasswordForm'])) {
            $model->attributes = $_POST['FindPasswordForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate()) {
                $email = urlencode($model->email);
                $this->redirect(array("/user/user/findpwdemailsd", 'mail' => $email));
            }
        }
        UrlClass::returnUrl('/user/login/login');
        $this->render('findpassword', array('model' => $model));
    }

    public function actionFindPwdEmailSd() {
        $this->layout = 'theme.views.layouts.RegisterContent';
        $mail_host = false;
        $url = $this->createUrl("/user/user/findpwdemailsd/mail/{$_GET['mail']}");
        $email = urldecode($_GET['mail']);
        if ($this->sentFindPasswordEmail($email)) {
            $message = $email;
            $temp = explode('@', $email);
            $mail_host = $temp[1];
        } else {
            $message = $_COOKIE['sent_email'];
        }
        $this->render('findpasswordSuccess', array('message' => $message, 'mail_host' => $mail_host, 'url' => $url));
    }

    protected function sentFindPasswordEmail($email) {
        $mail = Yii::createComponent('application.extensions.mailer.EMailer');
        $ConfigModel = new ConfigModel();
        $config = $ConfigModel->getConfig();
        $emailTitle = '亲爱的' . $config['sitename'] . '用户   ' . $email . "，找回密码邮件。";
        $code = substr(md5(uniqid(mt_rand(), true)), 0, 32);
        $url = $this->createUrl("/user/user/findpasswordverify", array('confirmation_token' => $code));
        $emailBody = '
           <table width="720" border="0" cellspacing="0" cellpadding="0">
		<tbody>
		<tr>
		<td style="line-height:24px">亲爱的' . $config['sitename'] . '会员！<br>
		请点击下面链接修改密码（链接72小时内有效）：<br>
		<a href="' . Yii::app()->request->hostInfo . $url . '" target="_blank">' . Yii::app()->request->hostInfo . $url . '</a>
		<br>
		如果您的邮箱不支持链接点击，请将以上链接地址拷贝到您的浏览器地址栏中。<br>
		如果您没有申请找回' . $config['sitename'] . '会员密码，请忽略此邮件
		</td>
		</tr>
		<tr>
		<td align="right" height="30">' . $config['sitename'] . '</td>
		</tr>
		<tr>
		<td align="right"><span times="" t="5" style="border-bottom: 1px dashed rgb(204, 204, 204);">' . date('Y-m-d', time()) . '</span></td>
		</tr>
		<tr>
		<td valign="middle" align="center" height="40" style="color:#999">（本邮件由系统自动发出，请勿回复。）</td>
		</tr>
		</tbody>
            </table>
            ';
        $MembersModel = new MembersModel();
        $member = $MembersModel->getMemberByEmail($email);
        if (!$member) {
            $_COOKIE['sent_email'] = "邮件尚未注册！";
            //Yii::app()->user->setFlash('sent_email', '邮件尚未注册！');
            return false;
        }
        $MembersActivationModel = new MembersActivationModel();
        if ($interval = $MembersActivationModel->JudgeFindPasswordSent($email)) {
            $interval = 120 - $interval;
            $_COOKIE['sent_email'] = "亲，您刚发送了一封邮件，请耐心等待！{$interval}秒后，还没收到请重发！";
            //Yii::app()->user->setFlash('sent_email', "亲，您刚发送了一封邮件，请耐心等待！{$interval}秒后，还没收到请重发！");
            return false;
        }
        if ($mail->sendEmail($email, $emailTitle, $emailBody)) {
            $endtime = $_SERVER['REQUEST_TIME'] + +72 * 3600;
            $MembersActivationModel->endtime = $endtime;
            $MembersActivationModel->status = 0;
            $MembersActivationModel->code = $code;
            $MembersActivationModel->email = $email;
            $MembersActivationModel->save();
            return true;
        }
        $_COOKIE['sent_email'] = "邮件发送失败！";
        //Yii::app()->user->setFlash('sent_email', '邮件发送失败！');
        return false;
    }

    public function actionFindPasswordVerify() {
        $MembersActivationModel = new MembersActivationModel();
        $code = $_GET['confirmation_token'];
        $message = $MembersActivationModel->judgeFindPwdVerify($code);
        if ($message['status'] < 1) {
            $email = urlencode($message['email']);
            $url = $this->createUrl("/user/user/findpwdemailsd", array('mail' => $email));
            $this->render('findpwdverify', array('message' => $message, 'url' => $url));
        } else {
            $model = new UpdatePasswordForm();
            if (isset($_POST['UpdatePasswordForm'])) {
                $model->attributes = $_POST['UpdatePasswordForm'];
                $model->email = $message['email'];
                // validate user input and redirect to the previous page if valid
                if ($model->validate()) {
                    $user = MembersModel::model()->find('email =  ?', array($model->email));
                    if ($user) {
                        $user->password = md5($model->password);
                        $user->update();
                    }
                    $this->redirect(array("/user/login/login"));
                }
            }
            UrlClass::returnUrl('user/user/findpasswordverify');
            $this->render('updatepwd', array('model' => $model));
        }
    }

    public function actionLogout() {
        Yii::app()->user->logout();
        UrlClass::returnUrl('/user/user/logout');
        $this->redirect(self::U('front/index/index'));
    }

}
